package app1.rapidsquare.com.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.core.ConnectionDetector;
import app1.rapidsquare.com.activity.R;

public class ProfileActivity extends ActionBarActivity {

    private ImageView mImageViewPhoto, mImageViewMessage, mImageViewCall, mImageViewEmail, mImageViewWebSite;
    private TextView mTextViewCode, mTextViewContactFullName, mTextViewContactProfession, mTextViewContactCompany,
            mTextViewContactMobile, mTextViewContactHome, mTextViewContactEmail, mTextViewContactWebSite,
            mTextViewContactSkype, mTextViewContactAddress, mTextViewContactInfo, mTextViewLinkedInName, mTextViewGooglePlusName, mTextViewFacebookName;
    private RelativeLayout mRelativeLayoutMobile, mRelativeLayoutEmail, mRelativeLayoutWebSite;
    private LinearLayout mLinearLayoutHome, mLinearLayoutSkype, mLinearLayoutAddress, mLinearLayoutInfo, mLinearlayoutLinkedIn, mLinearLayoutGooglePlus, mLinearLayoutFacebook;
    private User mUser;
    private EditText mEditTextNotes;
    private Button mButtonAccept, mButtonIgnore;
    protected ProgressDialog mProgressDialog;
    private ConnectionDetector mConnectionDetector;
    private TextView mTextViewInternetConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        mConnectionDetector = new ConnectionDetector(this);
        mProgressDialog = new ProgressDialog(ProfileActivity.this);
        mProgressDialog.setMessage("Please wait");

        if (getIntent().hasExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME)) {
            mUser = (User) getIntent().getSerializableExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME);
        }

        boolean isConnectContact = false;
        if (getIntent().hasExtra("IsConnectContact"))
            isConnectContact = getIntent().getBooleanExtra("IsConnectContact", false);

        LoadActionBar(isConnectContact);

        if (mUser == null)
            finish();
        mTextViewCode = (TextView) findViewById(R.id.textViewContactCode);
        mImageViewPhoto = (ImageView) findViewById(R.id.imageViewLogo);
        mTextViewContactFullName = (TextView) findViewById(R.id.textViewContactFullName);
        mTextViewContactProfession = (TextView) findViewById(R.id.textViewContactProfession);
        mTextViewContactCompany = (TextView) findViewById(R.id.textViewContactCompany);
        mTextViewContactMobile = (TextView) findViewById(R.id.textViewContactMobile);
        mTextViewContactHome = (TextView) findViewById(R.id.textViewContactHome);
        mTextViewContactEmail = (TextView) findViewById(R.id.textViewContactEmail);
        mTextViewContactSkype = (TextView) findViewById(R.id.textViewContactSkype);
        mTextViewContactAddress = (TextView) findViewById(R.id.textViewContactAddress);
        mTextViewContactInfo = (TextView) findViewById(R.id.textViewContactInfo);
        mTextViewLinkedInName = (TextView) findViewById(R.id.textViewContactLinkedInName);
        mTextViewGooglePlusName = (TextView) findViewById(R.id.textViewContactGooglePlusName);
        mTextViewFacebookName = (TextView) findViewById(R.id.textViewContactFacebookName);
        mRelativeLayoutMobile = (RelativeLayout) findViewById(R.id.relativeLayoutMobile);
        mRelativeLayoutEmail = (RelativeLayout) findViewById(R.id.relativeLayoutEmail);
        mRelativeLayoutWebSite = (RelativeLayout) findViewById(R.id.relativeLayoutWebSite);
        mLinearLayoutHome = (LinearLayout) findViewById(R.id.linearLayoutHome);
        mLinearLayoutSkype = (LinearLayout) findViewById(R.id.linearLayoutSkype);
        mLinearLayoutAddress = (LinearLayout) findViewById(R.id.linearLayoutAddress);
        mLinearLayoutInfo = (LinearLayout) findViewById(R.id.linearLayoutInfo);
        mImageViewMessage = (ImageView) findViewById(R.id.imageViewMessage);
        mImageViewCall = (ImageView) findViewById(R.id.imageViewCall);
        mImageViewEmail = (ImageView) findViewById(R.id.imageViewEmail);
        mImageViewWebSite = (ImageView) findViewById(R.id.imageViewWebSite);
        mTextViewContactWebSite = (TextView) findViewById(R.id.textViewContactWebSite);

        LinearLayout linearLayoutNotes = (LinearLayout) findViewById(R.id.linearLayoutNote);
        mEditTextNotes = (EditText) findViewById(R.id.editTextContactNotes);


        mButtonAccept = (Button) findViewById(R.id.buttonContactAccept);
        mButtonAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnAcceptOrIgnore(true, mUser);

            }
        });
        mButtonIgnore = (Button) findViewById(R.id.buttonContactIgnore);
        mButtonIgnore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnAcceptOrIgnore(false, mUser);
            }
        });
        if (isConnectContact) {
            linearLayoutNotes.setVisibility(View.GONE);
            mEditTextNotes.setVisibility(View.GONE);
        } else {
            mButtonAccept.setVisibility(View.GONE);
            mButtonIgnore.setVisibility(View.GONE);
        }


        mLinearlayoutLinkedIn = (LinearLayout) findViewById(R.id.linearLayoutLinkedIn);
        if (Utility.isNullOrEmpty(mUser.LinkedInId) || mUser.LinkedInId.equals("null"))
            mLinearlayoutLinkedIn.setVisibility(View.GONE);


        mLinearLayoutGooglePlus = (LinearLayout) findViewById(R.id.linearLayoutGooglePlus);
        if (Utility.isNullOrEmpty(mUser.GooglePlusId) || mUser.GooglePlusId.equals("null"))
            mLinearLayoutGooglePlus.setVisibility(View.GONE);


        mLinearLayoutFacebook = (LinearLayout) findViewById(R.id.linearLayoutFacebook);
        if (Utility.isNullOrEmpty(mUser.FacebookId) || mUser.FacebookId.equals("null"))
            mLinearLayoutFacebook.setVisibility(View.GONE);

        mTextViewInternetConnection = (TextView) findViewById(R.id.textViewInternetConnection);
    }

    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(
                mConnectionDetector,
                new IntentFilter(
                        android.net.ConnectivityManager.CONNECTIVITY_ACTION));

        if (!Utility.isNullOrEmpty(mUser.Code)) {
            Picasso picasso = Picasso.with(ProfileActivity.this);
            picasso.load(Utility.IMAGE_URL + "?Code=" + mUser.Code)
                    .placeholder(R.drawable.icon_temp)
                    .error(R.drawable.icon_temp)
                    .resizeDimen(R.dimen.image_size,
                            R.dimen.image_size).centerInside().into(mImageViewPhoto);
        }
        mTextViewCode.setText(getResources().getString(R.string.connect_id) + ": " + mUser.Code);
        mTextViewContactFullName.setText(mUser.FirstName + " " + mUser.LastName);
        mTextViewContactProfession.setText(mUser.Title);
        mTextViewContactCompany.setText(mUser.Company);
        mTextViewContactMobile.setText(formatPhoneNumber(mUser.Phone));
        mTextViewContactHome.setText("");
        mTextViewContactEmail.setText(mUser.Email);
        mTextViewContactSkype.setText("");
        mTextViewContactWebSite.setText(mUser.Site);
        String address = "";
        if (!Utility.isNullOrEmpty(mUser.City) && !Utility.isNullOrEmpty(mUser.State))
            address = mUser.City + ", " + mUser.State;

        if (Utility.isNullOrEmpty(mUser.City) && !Utility.isNullOrEmpty(mUser.State))
            address = mUser.State;

        if (Utility.isNullOrEmpty(mUser.State) && !Utility.isNullOrEmpty(mUser.City))
            address = mUser.City;

        mTextViewContactAddress.setText(address);
        mTextViewContactInfo.setText(mUser.Info);

        if (Utility.isNullOrEmpty(mUser.Phone)) {
            mRelativeLayoutMobile.setVisibility(View.GONE);

        } else {
            boolean hasTelephony = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
            if (hasTelephony) {
                mImageViewCall.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse("tel:" + mUser.Phone));
                        try {
                            startActivity(callIntent);

                        } catch (Exception ex) {
                            Utility.Log("call to number in ProfileActivity", ex);
                        }
                    }
                });


                mImageViewMessage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse("smsto:"));
                        intent.setType("vnd.android-dir/mms-sms");

                        intent.putExtra("address", new String(mUser.Phone));
                        try {
                            startActivity(intent);

                        } catch (Exception ex) {
                            Utility.Log("Send sms in ProfileActivity", ex);
                        }
                    }
                });
            } else {
                mImageViewCall.setVisibility(View.GONE);
                mImageViewMessage.setVisibility(View.GONE);
            }
        }

        if (Utility.isNullOrEmpty(mUser.Email)) {
            mRelativeLayoutEmail.setVisibility(View.GONE);
        } else {
            mImageViewEmail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        Intent emailIntent = new Intent(Intent.ACTION_SEND);
                        emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{mUser.Email});
                        emailIntent.setType("application/octet-stream");
                        startActivity(Intent.createChooser(emailIntent, "Send Email"));
                    } catch (Exception ex) {
                        Utility.Log("Send email in ProfileActivity", ex);
                    }
                }
            });
        }

        if (Utility.isNullOrEmpty(mUser.Site) || mUser.Site.equals("null")) {
            mRelativeLayoutWebSite.setVisibility(View.GONE);
        } else {
            mImageViewWebSite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://" + mUser.Site));
                        startActivity(intent);
                    } catch (Exception ex) {
                        Utility.Log("Open WebSite in ProfileActivity", ex);
                    }
                }
            });
        }

        if (Utility.isNullOrEmpty(mUser.City + "" + mUser.State))
            mLinearLayoutAddress.setVisibility(View.GONE);

        if (Utility.isNullOrEmpty(mUser.Info))
            mLinearLayoutInfo.setVisibility(View.GONE);
        else
            mLinearLayoutInfo.setVisibility(View.VISIBLE);

        if (Utility.isNullOrEmpty(mUser.Note))
            mEditTextNotes.setText("");
        else
            mEditTextNotes.setText(mUser.Note);

        if (!Utility.isNullOrEmpty(mUser.GooglePlusName))
            mTextViewGooglePlusName.setText(mUser.GooglePlusName);
        else
            mTextViewGooglePlusName.setText(getResources().getString(R.string.google_plus));

        if (!Utility.isNullOrEmpty(mUser.LinkedInName))
            mTextViewLinkedInName.setText(mUser.LinkedInName);
        else
            mTextViewLinkedInName.setText(getResources().getString(R.string.linked_in));

        if (!Utility.isNullOrEmpty(mUser.FacebookName))
            mTextViewFacebookName.setText(mUser.FacebookName);
        else
            mTextViewFacebookName.setText(getResources().getString(R.string.facebook));

        mLinearlayoutLinkedIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mUser.LinkedInId));
                startActivity(intent);
            }
        });

        mLinearLayoutGooglePlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://plus.google.com/" + mUser.GooglePlusId));
                startActivity(intent);
            }
        });

        mLinearLayoutFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + mUser.FacebookId));
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mConnectionDetector);
    }

    @Override
    public void onBackPressed() {
        if (mEditTextNotes.getVisibility() == View.VISIBLE && !mEditTextNotes.getText().toString().equals(mUser.Note)) {
            mUser.Note = mEditTextNotes.getText().toString();
            setResult(RESULT_OK, new Intent().putExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME, mUser));
        }
        super.onBackPressed();
        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("CurrentContact", mUser);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null
                && savedInstanceState.containsKey("CurrentContact"))
            mUser = (User) savedInstanceState.getSerializable("CurrentContact");
    }

    private void OnAcceptOrIgnore(final boolean status, final User user) {
        if (IsAvailableInternet()) {
            mTextViewInternetConnection.setVisibility(View.GONE);
            mProgressDialog.show();
            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... voids) {
                    String url = Utility.REPLY_NOTIFICATION_URL + "?userToken="
                            + Utility.getUserSession(ProfileActivity.this).UserToken + "&code="
                            + user.Code.trim() + "&agree=" + status;
                    return Utility.ConnectServer(url, Utility.RequestMethodType.GET, null);
                }

                @Override
                protected void onPostExecute(String s) {
                    mProgressDialog.dismiss();
                    if (status)
                        setResult(RESULT_OK, new Intent().putExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME, mUser));
                    else
                        setResult(RESULT_CANCELED, new Intent().putExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME, mUser));
                    finish();
                }
            }.execute();
        } else
            mTextViewInternetConnection.setVisibility(View.VISIBLE);
    }

    private void LoadActionBar(boolean isConnectContact) {
        ActionBar mActionBar = getSupportActionBar();
        if (mActionBar != null) {
            mActionBar.setDisplayShowHomeEnabled(false);
            mActionBar.setHomeButtonEnabled(false);
            mActionBar.setDisplayShowTitleEnabled(false);
            LayoutInflater mInflater = LayoutInflater.from(this);

            View mCustomView = mInflater.inflate(R.layout.action_bar_with_back, null);

            ImageView mImageViewBack = (ImageView) mCustomView
                    .findViewById(R.id.textViewBack);
            mImageViewBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });

            RelativeLayout relativeLayout = (RelativeLayout) mCustomView.findViewById(R.id.relativeLayoutSave);
            TextView textViewTitle = (TextView) mCustomView.findViewById(R.id.textViewTitle);
            ImageView imageViewMenu = (ImageView) mCustomView.findViewById(R.id.imageViewMenu);
            if (!isConnectContact) {
                relativeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(Intent.ACTION_INSERT);
                        i.setType(ContactsContract.Contacts.CONTENT_TYPE);
                        i.putExtra(ContactsContract.Intents.Insert.NAME, mUser.FirstName + " " + mUser.LastName);
                        i.putExtra(ContactsContract.Intents.Insert.PHONE, mUser.Phone);
                        i.putExtra(ContactsContract.Intents.Insert.EMAIL, mUser.Email);
                        startActivity(i);
                    }
                });
                textViewTitle.setText(getResources().getString(R.string.save_to_phonebook));
                imageViewMenu.setImageResource(R.drawable.plus);
            } else {
                textViewTitle.setVisibility(View.GONE);
                imageViewMenu.setVisibility(View.GONE);
            }


            mActionBar.setCustomView(mCustomView);
            mActionBar.setDisplayShowCustomEnabled(true);
        }
    }

    protected boolean IsAvailableInternet() {
        return mConnectionDetector.getConnectingStatus();
    }

    private static String formatPhoneNumber(String s) {

        int localNumberMaxLength = 7;
        int areaCodeMaxLength = 3;
        int countryCodeMaxLength = 3;
        String removerWhiteSpacePattern = "(\\w)(\\s+)([\\.,])";
        s = s.replaceAll(removerWhiteSpacePattern, "");

        StringBuffer resulsString = new StringBuffer();
        String newNumber = new String();

        // Strip all non-numbers
        for (int i = 0; i < s.length(); i++) {

            if (Character.isDigit(s.charAt(i))) {
                newNumber += (s.charAt(i));
            }
        }


        if (newNumber.length() > localNumberMaxLength + areaCodeMaxLength + countryCodeMaxLength) {
            newNumber = newNumber.substring(0, localNumberMaxLength + areaCodeMaxLength + countryCodeMaxLength);
        }

        int localNumberLength = Math.min(newNumber.length(), localNumberMaxLength);
        if (localNumberLength > 0) {
            String number = newNumber.substring(newNumber.length() - localNumberLength);
            resulsString.append(number);
            if (resulsString.length() > 3) {
                resulsString.insert(3, "-");
            }
        }

        if (newNumber.length() > localNumberMaxLength) {

            int areaCodeLength = Math.min(newNumber.length() - localNumberMaxLength, areaCodeMaxLength);

            int startPosition = newNumber.length() - localNumberLength - areaCodeLength;

            String areaCodeString = newNumber.substring(startPosition, startPosition + areaCodeLength);

            areaCodeString = String.format("(%s)", areaCodeString);

            resulsString.insert(0, areaCodeString);
        }

        if (newNumber.length() > localNumberMaxLength + areaCodeMaxLength) {

            int countryCodeLength = Math.min(newNumber.length() - localNumberMaxLength - areaCodeMaxLength, countryCodeMaxLength);

            String countryCode = newNumber.substring(0, countryCodeLength);

            countryCode = String.format("+%s", countryCode);

            resulsString.insert(0, countryCode);
        }

        return resulsString.toString();
    }
}
